/**
 * 信任卡牌管理器
 * 管理信任卡牌的状态、数据和操作
 */

class TrustCardManager {
  constructor() {
    this.storageKey = 'trustCardData'
    this.trustCards = []
    this.trustHistory = []
    this.initDefaultCards()
  }

  /**
   * 初始化默认卡牌
   */
  initDefaultCards() {
    this.trustCards = [
      {
        id: 'cooperation_card',
        name: '协作卡',
        icon: '🤝',
        description: '建立合作关系，提升双方信任值',
        type: 'cooperation',
        baseTrustValue: 50,
        currentTrustValue: 50,
        maxTrustValue: 100,
        effects: ['协作加成', '信任建立'],
        rarity: 'common'
      },
      {
        id: 'loyalty_card',
        name: '忠诚卡',
        icon: '💎',
        description: '展现忠诚，获得长期信任奖励',
        type: 'loyalty',
        baseTrustValue: 30,
        currentTrustValue: 30,
        maxTrustValue: 100,
        effects: ['忠诚奖励', '长期合作'],
        rarity: 'rare'
      },
      {
        id: 'betrayal_card',
        name: '背叛卡',
        icon: '⚠️',
        description: '背叛行为，降低信任但可能获得短期收益',
        type: 'betrayal',
        baseTrustValue: 70,
        currentTrustValue: 70,
        maxTrustValue: 100,
        effects: ['短期收益', '信任损失'],
        rarity: 'common'
      },
      {
        id: 'forgiveness_card',
        name: '宽恕卡',
        icon: '🙏',
        description: '宽恕他人，修复破裂的信任关系',
        type: 'forgiveness',
        baseTrustValue: 20,
        currentTrustValue: 20,
        maxTrustValue: 100,
        effects: ['信任修复', '关系重建'],
        rarity: 'epic'
      },
      {
        id: 'alliance_card',
        name: '联盟卡',
        icon: '⚔️',
        description: '建立联盟，获得团队信任加成',
        type: 'alliance',
        baseTrustValue: 60,
        currentTrustValue: 60,
        maxTrustValue: 100,
        effects: ['团队加成', '联盟奖励'],
        rarity: 'legendary'
      }
    ]
  }

  /**
   * 获取所有卡牌
   */
  getAllCards() {
    return this.trustCards
  }

  /**
   * 根据ID获取卡牌
   */
  getCardById(cardId) {
    return this.trustCards.find(card => card.id === cardId)
  }

  /**
   * 更新卡牌信任值
   */
  updateCardTrust(cardId, trustChange, reason = '信任变化') {
    const card = this.getCardById(cardId)
    if (!card) return false

    const oldTrustValue = card.currentTrustValue
    card.currentTrustValue = Math.max(0, Math.min(100, card.currentTrustValue + trustChange))

    // 记录信任变化历史
    this.recordTrustChange(cardId, oldTrustValue, card.currentTrustValue, reason)

    // 保存数据
    this.saveData()

    return true
  }

  /**
   * 记录信任变化
   */
  recordTrustChange(cardId, oldValue, newValue, reason) {
    const change = {
      id: Date.now(),
      cardId,
      oldValue,
      newValue,
      change: newValue - oldValue,
      reason,
      timestamp: new Date().toISOString()
    }

    this.trustHistory.unshift(change)

    // 限制历史记录数量
    if (this.trustHistory.length > 50) {
      this.trustHistory.splice(50)
    }
  }

  /**
   * 获取卡牌信任等级
   */
  getTrustLevel(trustValue) {
    if (trustValue >= 80) return 'high'
    if (trustValue >= 50) return 'medium'
    if (trustValue >= 20) return 'low'
    return 'broken'
  }

  /**
   * 获取信任等级文本
   */
  getTrustLevelText(trustValue) {
    const levels = {
      high: '高度信任',
      medium: '一般信任',
      low: '低度信任',
      broken: '信任破裂'
    }
    return levels[this.getTrustLevel(trustValue)]
  }

  /**
   * 计算信任效果
   */
  calculateTrustEffects(trustValue) {
    const effects = []

    if (trustValue >= 90) {
      effects.push({
        id: 'divine_blessing',
        name: '神圣祝福',
        icon: '✨',
        description: '获得神圣祝福，所有效果翻倍',
        multiplier: 2
      })
    }

    if (trustValue >= 80) {
      effects.push({
        id: 'perfect_trust',
        name: '完美信任',
        icon: '💎',
        description: '完美信任状态，获得额外奖励',
        bonus: 20
      })
    }

    if (trustValue >= 60) {
      effects.push({
        id: 'cooperation_boost',
        name: '协作加成',
        icon: '🤝',
        description: '协作效果提升30%',
        boost: 0.3
      })
    }

    if (trustValue <= 20) {
      effects.push({
        id: 'suspicion',
        name: '怀疑状态',
        icon: '⚠️',
        description: '处于怀疑状态，效果降低',
        penalty: 0.5
      })
    }

    if (trustValue <= 10) {
      effects.push({
        id: 'broken_trust',
        name: '信任破裂',
        icon: '💔',
        description: '信任完全破裂，需要修复',
        critical: true
      })
    }

    return effects
  }

  /**
   * 执行信任行动
   */
  performTrustAction(cardId, actionType, targetCardId = null) {
    const card = this.getCardById(cardId)
    if (!card) return { success: false, message: '卡牌不存在' }

    let trustChange = 0
    let message = ''

    switch (actionType) {
      case 'cooperation':
        trustChange = 15
        message = '协作成功，信任值提升'
        break
      case 'betrayal':
        trustChange = -25
        message = '背叛行为，信任值大幅下降'
        break
      case 'forgiveness':
        trustChange = 10
        message = '宽恕行为，信任值小幅提升'
        break
      case 'loyalty':
        trustChange = 20
        message = '忠诚表现，信任值显著提升'
        break
      case 'repair':
        trustChange = 30
        message = '信任修复，信任值大幅提升'
        break
      default:
        return { success: false, message: '未知行动类型' }
    }

    // 应用信任变化
    this.updateCardTrust(cardId, trustChange, `${actionType}行动`)

    // 如果有关联卡牌，也更新其信任值
    if (targetCardId) {
      const targetCard = this.getCardById(targetCardId)
      if (targetCard) {
        const targetChange = Math.floor(trustChange * 0.5) // 关联卡牌获得一半效果
        this.updateCardTrust(targetCardId, targetChange, `关联${actionType}行动`)
      }
    }

    return {
      success: true,
      message,
      trustChange,
      newTrustValue: card.currentTrustValue
    }
  }

  /**
   * 获取信任统计
   */
  getTrustStats() {
    const totalCards = this.trustCards.length
    const highTrustCards = this.trustCards.filter(card => card.currentTrustValue >= 80).length
    const mediumTrustCards = this.trustCards.filter(card => 
      card.currentTrustValue >= 50 && card.currentTrustValue < 80
    ).length
    const lowTrustCards = this.trustCards.filter(card => 
      card.currentTrustValue >= 20 && card.currentTrustValue < 50
    ).length
    const brokenTrustCards = this.trustCards.filter(card => card.currentTrustValue < 20).length

    const averageTrust = this.trustCards.reduce((sum, card) => sum + card.currentTrustValue, 0) / totalCards

    return {
      totalCards,
      highTrustCards,
      mediumTrustCards,
      lowTrustCards,
      brokenTrustCards,
      averageTrust: Math.round(averageTrust)
    }
  }

  /**
   * 获取信任历史
   */
  getTrustHistory(limit = 10) {
    return this.trustHistory.slice(0, limit)
  }

  /**
   * 重置所有卡牌信任值
   */
  resetAllTrust() {
    this.trustCards.forEach(card => {
      card.currentTrustValue = card.baseTrustValue
    })
    this.trustHistory = []
    this.saveData()
  }

  /**
   * 保存数据到本地存储
   */
  saveData() {
    try {
      const data = {
        trustCards: this.trustCards,
        trustHistory: this.trustHistory,
        lastUpdate: new Date().toISOString()
      }
      uni.setStorageSync(this.storageKey, JSON.stringify(data))
      return true
    } catch (error) {
      console.error('保存信任卡牌数据失败:', error)
      return false
    }
  }

  /**
   * 从本地存储加载数据
   */
  loadData() {
    try {
      const data = uni.getStorageSync(this.storageKey)
      if (data) {
        const parsedData = JSON.parse(data)
        this.trustCards = parsedData.trustCards || this.trustCards
        this.trustHistory = parsedData.trustHistory || []
        return true
      }
    } catch (error) {
      console.error('加载信任卡牌数据失败:', error)
    }
    return false
  }

  /**
   * 导出信任数据
   */
  exportTrustData() {
    return {
      trustCards: this.trustCards,
      trustHistory: this.trustHistory,
      stats: this.getTrustStats(),
      exportTime: new Date().toISOString()
    }
  }

  /**
   * 导入信任数据
   */
  importTrustData(data) {
    try {
      if (data.trustCards) {
        this.trustCards = data.trustCards
      }
      if (data.trustHistory) {
        this.trustHistory = data.trustHistory
      }
      this.saveData()
      return true
    } catch (error) {
      console.error('导入信任数据失败:', error)
      return false
    }
  }
}

// 创建单例实例
const trustCardManager = new TrustCardManager()

export default trustCardManager

